#!/usr/bin/env python
# coding=utf-8

import logging
import cgi
import wsgiref.handlers

import xml.dom.minidom
import StringIO


from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache


import os
from google.appengine.ext.webapp import template

class Point(db.Model):
    author = db.UserProperty()
    name = db.StringProperty()
    tag = db.StringProperty()
    comment = db.StringProperty(multiline=True)    
    date = db.DateTimeProperty(auto_now_add=True)
    latlng = db.GeoPtProperty()
    
class Line(db.Model):
    author = db.UserProperty()
    name = db.StringProperty()
    tag = db.StringProperty()
    comment = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    lineClosed = db.BooleanProperty()
    
    points = db.StringListProperty()
    

class Tag(db.Model):
    tag = db.StringProperty()
    author = db.UserProperty()
    comment = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    ispublic = db.StringProperty() #public friend pal private
    
   
class Friend(db.Model):
    author = db.UserProperty()
    entity = db.UserProperty()
    comment =  db.StringProperty()
    nickname = db.StringProperty()
    
class Family(db.Model):
    author = db.UserProperty()
    entity = db.UserProperty()
    comment =  db.StringProperty()
    nickname = db.StringProperty()
    relation = db.StringProperty()

class HomeHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user :
            self.response.headers['Content-Type'] = 'text/html'
            path = os.path.join(os.path.dirname(__file__), 'user.html')
            template_values = {"logout":users.create_logout_url('/'),}            
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
            
class MainPage(webapp.RequestHandler):
  def get(self):
    
    
    self.response.headers['Content-Type'] = 'text/html'
    path = os.path.join(os.path.dirname(__file__), 'index.html')    
    template_values = {}
    
    # FIXME remove to ajax call
    #result = urlfetch.fetch('http://www.google.com/ig/api?hl=zh-CN&weather=,,,39920000,116469996')
    
    weatherCache = memcache.get("weather")
    
    if weatherCache is not None:
        logging.info("Memcache get.")
        template_values = weatherCache
    else:
        result = urlfetch.fetch('http://www.google.com/ig/api?hl=en-us&weather=,,,39920000,116469996')
        
        if result.status_code == 200:
            doc = xml.dom.minidom.parse(StringIO.StringIO(str(result.content)))
            current = doc.getElementsByTagName("current_conditions")[0];
            condition = current.getElementsByTagName("condition")[0].getAttribute("data")
            temp_c = current.getElementsByTagName("temp_c")[0].getAttribute("data")
            humidity = current.getElementsByTagName("humidity")[0].getAttribute("data")
            wind = current.getElementsByTagName("wind_condition")[0].getAttribute("data")
            icon  = current.getElementsByTagName("icon")[0].getAttribute("data")
            template_values = {"weather":"got", "condition":condition, "temp_c":temp_c, "humidity":humidity,"wind":wind, "icon":icon}        
            
            if not memcache.add("weather", template_values, 3600):
                logging.error("Memcache set failed.")
            else:
                logging.error("Memcache set ok")
   
    if users.get_current_user():
        template_values["logout"] = users.create_logout_url('/')                    
    
    self.response.out.write(template.render(path, template_values))   

class LineHandler(webapp.RequestHandler):
    pass;
    
class PointHandler(webapp.RequestHandler):    
    def get(self):
        
        logging.info(self.request.uri)
        
        user = users.get_current_user()
        if user :
            action = self.request.get("action")
            name = self.request.get('name')
            tags = self.request.get('tags')
            comment = self.request.get('comment')

            if action == "create" :

                point = Point()
                point.author = user
                point.name = name
                point.tag = tags
                point.comment = comment
                point.latlng = db.GeoPt(self.request.get('lat'),self.request.get('lon'))                
                point.put()                                
                self.response.out.write("ok")
                
            elif action == "list" :
                tags = db.GqlQuery("SELECT * FROM Tag ORDER BY date DESC ")
                
                self.response.headers['Content-Type'] = 'text/xml'
                self.response.out.write('<?xml version="1.0"  encoding="UTF-8"?>')
                self.response.out.write('<entities>')
                for tag in tags:
                    self.response.out.write(tag.to_xml())
                    #self.response.out.write("<li><ul style='list-style:none;'>"+"<li>"+"Name: "+tag.tag+"</li>"+"<li>"+tag.comment+"</li>"+ "<li>"+tag.author.email()+"</li>"+"<li>"+tag.comment+"</li>"+"</ul></li>")
                self.response.out.write('</entities>')
                
            elif action == "delete" :
                if users.is_current_user_admin():
                    tagStr = self.request.get('tag')
                    if tagStr:
                        tags = db.GqlQuery("SELECT * FROM Tag where tag = :1", tagStr)
                        for tag in tags:
                            tag.delete()
                        self.response.out.write("ok")
                    else:
                        pass;
                    
            elif action == "deleteAll" :
                if users.is_current_user_admin():
                    pass;
                else:
                    pass;
                
            elif action == "update":                
                query = GqlQuery("SELECT * FROM Tag WHERE tag = :1", self.request.get('tag'))                
                if query.count():
                    for tag in query:
                          #tag.author = user
                          #tag.tag = self.request.get('tag')
                          tag.comment = self.request.get('comment')
                    db.put(query)                    
                else:
                    atag = Tag()
                    atag.author = user
                    atag.tag = self.request.get('tag')
                    atag.comment = self.request.get('comment')
                    atag.put()                               
                self.response.out.write("ok")                
            else:
                pass;
        else:
            self.redirect(users.create_login_url(self.request.uri))
            

class TagHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user :
            action = self.request.get("action")
            if action == "create" :
                if not self.request.get('tag'):
                    self.response.out.write("failed!")
                    return                    
                tag = Tag()
                tag.author = user
                tag.tag = self.request.get('tag')
                tag.comment = self.request.get('comment')
                tag.ispublic = self.request.get('ispublic')
                
                tag.put()
                
                self.response.out.write("ok")
                
            elif action == "list" : #FIXME change to  xml or json
                tags = db.GqlQuery("SELECT * FROM Tag ORDER BY date DESC ")

                self.response.headers['Content-Type'] = 'text/xml'
                self.response.out.write('<?xml version="1.0"  encoding="UTF-8"?>')
                self.response.out.write('<entities>')
                for tag in tags:
                    self.response.out.write(tag.to_xml())
                    #self.response.out.write("<li><ul style='list-style:none;'>"+"<li>"+"Name: "+tag.tag+"</li>"+"<li>"+tag.comment+"</li>"+ "<li>"+tag.author.email()+"</li>"+"<li>"+tag.comment+"</li>"+"</ul></li>")
                self.response.out.write('</entities>')
                
                
                '''
                self.response.out.write('<html><body>')
                self.response.out.write('<ul>')
                for tag in tags:
                    self.response.out.write("<li><ul style='list-style:none;'>"+"<li>"+"Name: "+tag.tag+"</li>"+"<li>"+tag.comment+"</li>"+ "<li>"+tag.author.email()+"</li>"+"<li>"+tag.comment+"</li>"+"</ul></li>")
                self.response.out.write('</ul>')
                self.response.out.write('</body></html>')
                '''
                
            elif action == "delete" :
                if users.is_current_user_admin():
                    tagStr = self.request.get('tag')
                    if tagStr:
                        tags = db.GqlQuery("SELECT * FROM Tag where tag = :1", tagStr)
                        for tag in tags:
                            tag.delete()
                        self.response.out.write("ok")
                    else:
                        tags = db.GqlQuery("SELECT * FROM Tag where tag = :1",'' )
                        
                        #FIXME db.deleteAll(tags)??
                        for tag in tags:
                            tag.delete()
                        self.response.out.write("ok")

                    
            elif action == "deleteAll" :
                if users.is_current_user_admin():
                    pass;
                else:
                    pass;
                
            elif action == "update":                
                query = GqlQuery("SELECT * FROM Tag WHERE tag = :1", self.request.get('tag'))                
                if query.count():
                    for tag in query:
                          #tag.author = user
                          #tag.tag = self.request.get('tag')
                          tag.comment = self.request.get('comment')
                    db.put(query)                    
                else:
                    atag = Tag()
                    atag.author = user
                    atag.tag = self.request.get('tag')
                    atag.comment = self.request.get('comment')
                    atag.put()                               
                self.response.out.write("ok")                
            else:
                pass;
        else:
            self.redirect(users.create_login_url(self.request.uri))
        
class  ListHandler(webapp.RequestHandler):
    def get(self):        
        type = self.request.get('type')
        tag = self.request.get('tag')       
        
        #if type not in ["Point","Line","Polygon","Diary"]:
        #    self.response.set_status(404,"resoureces not found!")
        #    return;
        
        if tag:
            gql = db.GqlQuery("SELECT * FROM "+type+" where tag = :1 ORDER BY date DESC ", tag)
        else:
            gql = db.GqlQuery("SELECT * FROM "+type+" ORDER BY date DESC ")
            
        offset = self.request.get('offset')        
        results = []        
        if offset:
            results = gql.fetch(10,offset);
        else:
            results = gql.fetch(10);
            
        self.response.out.write('<?xml version="1.0"  encoding="UTF-8"?>')
        self.response.out.write('<entities>')
        for result in results:
            self.response.out.write(result.to_xml())        
        self.response.out.write('</entities>')

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    application = webapp.WSGIApplication(
      [
        ('/', MainPage),
        ('/point', PointHandler),
        ('/tag', TagHandler),
        ('/line', LineHandler),
        
        ('/user/list', ListHandler),
        ('/user', HomeHandler),

      ],
      debug=True
    )
    
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()